import { NextFunction, Request, Response } from 'express'
import { Unauthorized } from 'http-errors'
import jwt from 'jsonwebtoken'
import adminService from '../modules/admin/admin.services'
import { AdminWithoutPassword } from '../modules/admin/admin.types'

export default async function (req: Request, res: Response, next: NextFunction) {
  // 判断 Token 是否存在
  const { token } = req.headers
  if (!token) {
    throw new Unauthorized('当前接口需要认证才能访问。')
  }
  // 确保 token 是字符串类型
  if (Array.isArray(token)) {
    throw new Unauthorized('Token 格式不正确。')
  }
  // 验证 token 是否正确
  const decoded = jwt.verify(token, process.env.SECRET!)

  // 从 jwt 中，解析出之前存入的 adminId
  const { adminId } = decoded as { adminId: number }
  const admin = await adminService.getAdminById(adminId)

  if (!admin) {
    throw new Unauthorized('当前用户不存在。')
  }
  ;(req as Request & { admin?: AdminWithoutPassword }).admin = admin

  next()
}
